/*globals $, chrome, console, window, document, localStorage*/
if (typeof $.moreddit === 'undefined' &&  typeof $.moreddit.state === 'undefined'){
    $.moreddit.state = null;
}
$("body").append("<div id='rreContainer'><div id='rreShowAll'></div><div id='rreMinimalHeader'></div><div id='rreJustContent'></div></div>");

var inactive = { 
        "showAll" : "transparent url('"+chrome.extension.getURL("buttons.png")+"') 0 0 no-repeat",
        "minimalHeader" : "transparent url('"+chrome.extension.getURL("buttons.png")+"') -20px 0 no-repeat",
        "justContent" : "transparent url('"+chrome.extension.getURL("buttons.png")+"') -40px 0 no-repeat"
    },
    active = {
        "showAll" : "transparent url('"+chrome.extension.getURL("buttons.png")+"') 0 -20px no-repeat",
        "minimalHeader" : "transparent url('"+chrome.extension.getURL("buttons.png")+"') -20px -20px no-repeat",
        "justContent" : "transparent url('"+chrome.extension.getURL("buttons.png")+"') -40px -20px no-repeat"
     };

function convertQueryToObj(query){
    var obj = {};

    query.replace(/\b([^&=]*)=([^&=]*)\b/g, function (m, a, d) {
        if (typeof obj[a] != 'undefined') {
            obj[a] += ',' + d;
        } else {
            obj[a] = d;
        }
    });

    return obj;
}

function fetchMore(){
    // Select last next/prev set as well as last anchor in set, that will be the next link.
    var nextPrev= $(".nextprev:last"),
        next = $("a:last", nextPrev),
        uri = "",
        params = {},
        baseUri = "";
   
    if (next.length <= 0){
        return;
    }
    uri = next.attr('href');
    params = convertQueryToObj(uri.substring(uri.indexOf("?")));
    baseUri = uri.substring(0, uri.indexOf("?"));

    nextPrev.html("Loading more links please wait...");
    $.get(baseUri, params, function(data){
        var doc = $(data),
            links = $("#siteTable", doc).children(),
            newNextPrev = $(".nextprev:last", doc),
            mainSiteTable = $('#siteTable');

        mainSiteTable.append(links);
        nextPrev.remove();
        mainSiteTable.parent().append(newNextPrev);

        $.moreddit.loading = false;
    });
}

function toggleView(state, landing){
    switch(state){
        case "min":
            if (!landing) {
                if ($.moreddit.state === 'content') {
                    $("#header-bottom-left").hide();
                    $("#header").show('slide',{direction: 'up', distance:"18px"});
                } else {
                    $("#header-bottom-left").hide('slide',{direction: 'up'});
                }

                if ($.moreddit.state === null || $.moreddit.state === state){
                    $(".side").hide('slide', {direction: 'right'});
                    $(".footer-parent").hide('slide', {direction: 'down'});
                }
            }

            $.moreddit.state = localStorage.moreddit =  "min";
            $("#rreShowAll").css("background", inactive.showAll);
            $("#rreMinimalHeader").css("background", active.minimalHeader);
            $("#rreJustContent").css("background", inactive.justContent);
          
            break;
         case "content":
            if (!landing) {
                $("#header").hide('slide', {direction: 'up'});
                if ($.moreddit.state === null || $.moreddit.state === state){
                    $(".side").hide('slide', {direction: 'right'});
                    $(".footer-parent").hide('slide', {direction: 'down'});
                }
            }

            $.moreddit.state = localStorage.moreddit =  "content";
            $("#rreShowAll").css("background", inactive.showAll);
            $("#rreMinimalHeader").css("background", inactive.minimalHeader);
            $("#rreJustContent").css("background", active.justContent);
            break;
         default:
            if (!landing) {
                if ($.moreddit.state === 'content') {
                    $("#header").show('slide', {direction: 'up'});  
                }
          
                $("#header-bottom-left").show('slide', {direction: 'up'});
                
                $(".side").show('slide', {direction: 'right'});
            $(".footer-parent").show('slide', {direction: 'down'});
            }

            $.moreddit.state = localStorage.moreddit =  null;
            $("#rreShowAll").css("background", active.showAll);
            $("#rreMinimalHeader").css("background", inactive.minimalHeader);
            $("#rreJustContent").css("background", inactive.justContent); 
            break;
    }
}

$("#rreShowAll").css("background", active.showAll)
    .click(function (){
        if($.moreddit.state === null){
            //already active
            return false;
        }
        
        toggleView('null');
    })
    .mouseenter(function () {
        $(this).fadeTo('fast', 1);
    })
    .mouseleave(function () {
        $(this).fadeTo('fast', 0.5);        
    });

$("#rreMinimalHeader").css("background", inactive.minimalHeader)
    .click(function (){
        if($.moreddit.state === "min"){
            //already active
            return false;
        }    
        
        toggleView('min');
    })
    .mouseenter(function () {
        $(this).fadeTo('fast', 1);
    })
    .mouseleave(function () {
        $(this).fadeTo('fast', 0.5);        
    });
 
$("#rreJustContent").css("background", inactive.justContent)
    .click(function (){
        if($.moreddit.state === "content"){
            //already active
            return false;
        }
        
        toggleView("content");
    })
    .mouseenter(function () {
        $(this).fadeTo('fast', 1);
    })
    .mouseleave(function () {
        $(this).fadeTo('fast', 0.5);        
    });

if ($("#rreInitStyle").length > 0){
    toggleView($.moreddit.state, true);
    
}


$(window).scroll( function (){
    var height = parseInt($(document).height(), 10),
        scrollTop = parseInt($(window).scrollTop(), 10),
        winheight = window.innerHeight,
        scrollPos = scrollTop + winheight;

    if (Math.ceil(scrollPos/height*100) > 70 && 
        !$.moreddit.loading &&
        $.moreddit.prevTop < scrollTop)
    {
        $.moreddit.loading = true;
        fetchMore();
    }

    $.moreddit.prevTop = scrollTop;
});


